package com.jed.xxh.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.widget.ImageView;

import com.jed.xxh.application.BaseApplication;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;

/**
 * 项目名：SmartButler<br/>
 * 包名：  com.jed.xxh.utils<br/>
 * 作者：徐晓辉<br/>
 * 创建日期：2018/11/30 8:58<br/>
 * 描述：封装图片加载框架-----Picasso<br/>
 */
public class PicassoUtil {

    /**
     * 说明：默认加载图片<br/>
     * 参数：<br/>
     * url：图片地址<br/>
     * imageView：存放图片的ImageView<br/>
     */
    public static void loadImgView(String url, ImageView imageView) {
        Picasso
                .with(BaseApplication.getAppContext())
                .load(url)
                .into(imageView);
    }


    /**
     * 说明：默认加载图片（指定大小）<br/>
     * 参数：<br/>
     * url：图片地址<br/>
     * width：图片宽度<br/>
     * height：图片高度<br/>
     * imageView：存放图片的ImageView<br/>
     */
    public static void loadImgViewSize(String url, int width, int height, ImageView imageView) {
        Picasso
                .with(BaseApplication.getAppContext())
                .load(url)
                .resize(width, height)
                .centerCrop()
                .into(imageView);
    }


    /**
     * 说明：默认加载图片（有默认图片）<br/>
     * 参数：<br/>
     * url：图片地址<br/>
     * loadImg：加载成功的图片<br/>
     * errorImg：加载失败（默认）的图片<br/>
     * imageView：存放图片的ImageView<br/>
     */
    public static void loadImgViewHolder(String url, int loadImg, int errorImg, ImageView imageView) {
        Picasso
                .with(BaseApplication.getAppContext())
                .load(url)
                .placeholder(loadImg)
                .error(errorImg)
                .into(imageView);
    }

    /**
     * 说明：裁剪图片<br/>
     * 参数：<br/>
     * url：图片地址<br/>
     * imageView：存放图片的ImageView<br/>
     */
    public static void loadImgViewCrop(String url, ImageView imageView){
        Picasso
                .with(BaseApplication.getAppContext())
                .load(url)
                .transform(new CropSquareTransformation())
                .into(imageView);
    }

    /**
     * 按比例裁剪图片 矩形
     */
    private static class CropSquareTransformation implements Transformation {
        @Override
        public Bitmap transform(Bitmap source) {
            int size = Math.min(source.getWidth(), source.getHeight());
            int x = (source.getWidth() - size) / 2;
            int y = (source.getHeight() - size) / 2;
            Bitmap result = Bitmap.createBitmap(source, x, y, size, size);
            if (result != source) {
                //回收
                source.recycle();
            }
            return result;
        }



        @Override public String key() { return "square()"; }
    }


}
